package com.thortec.farmsys.controller.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * @auther ny by:dbw
 * @create 2018-11-25
 */
@RestController
@RequestMapping("upload")
public class FileUploadController{

    @Value("${img.upload.filepath}")
    private String upload_path;

    @Value("${img.server.path}")
    private String img_server_path;


    /**
     * 返回图片公共接口
     * @param file
     * @param isLayui  是否是layui接口 0不是  1是
     * @return
     */
    @RequestMapping("/img")
    public Object imgUpload(@RequestParam("file")MultipartFile file,@RequestParam(value = "type",required = false,defaultValue = "0") int isLayui){
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();   // 文件名

        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名 String filePath = "D://temp-rainy//";
        // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(upload_path + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
        String filename = img_server_path+ fileName;
        System.out.println(filename);
        return success(filename,isLayui);

    }

    public JSONObject fail(String err) {
        JSONObject object = new JSONObject();
        object.put("status", "FAIL");
        object.put("msg", err);
        object.put("code", 1);
        return object;
    }

    /**
     * {
     "code": 0 //0表示成功，其它失败
     ,"msg": "" //提示信息 //一般上传失败后返回
     ,"data": {
     "src": "图片路径"
     ,"title": "图片名称" //可选
     }
     }
     * @param url
     * @return
     */

    public JSONObject success(String url,int islayui) {
        JSONObject object = new JSONObject();
        object.put("status", "SUCCESS");
        object.put("code", 0);
        if(islayui==1){
            HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("src",url);
            object.put("data",objectObjectHashMap);
        }else{
            object.put("url",url);
        }
        return object;
    }


}
